//
//  IMProcessMessage.m
//  IMChezhil
//
//  Created by zhangliucheng on 15/7/23.
//  Copyright (c) 2015年 CheZhil. All rights reserved.
//

#import "IMProcessMessage.h"
#import "IMMessageManager.h"
#import "IMCommandMessage.h"
#import "IMTextMessage.h"
#import "IMImageMessage.h"
#import "IMAudioMessage.h"
#import "IMConstants.h"
#import "IMMessage.h"
#import "IMCore.h"
#import "IMTool.h"
#import "IMLoginReceiver.h"
#import "IMService.h"
#import "IMMessageReceiver.h"
#import "IMNotificationReceiver.h"

@implementation IMProcessMessage

+ (void)processSendMessage:(GCDAsyncSocket *)sock {
    IMMessage *message = [[IMCore shareInstance] getSendMessage];
    if (Nil != message) {
        if ([message isKindOfClass:[IMUserMessage class]]) {
            [IMProcessMessage sendUserMessage:sock message:(IMUserMessage *)message];
        } else if ([message isKindOfClass:[IMCommandMessage class]]) {
            [IMProcessMessage sendCommandMessage:sock message:(IMCommandMessage *)message];
        }
    } else {
        // 发送心跳包
    }
}

+ (void)sendUserMessage:(GCDAsyncSocket *)sock message:(IMUserMessage *)msg {
    if ([msg isKindOfClass:[IMImageMessage class]]) {
        // 上传图片
        [IMTool uploadImage:(IMImageMessage *)msg];
    } else if([msg isKindOfClass:[IMAudioMessage class]]) {
        // 上传语音
        [IMTool uploadAudio:(IMAudioMessage *)msg];
    }
    [sock writeData:[msg sendData] withTimeout:-1 tag:2];

    if (connectState == connect_success) {
        msg.sentStatus = SentStatusArrived;      // 标示为发送成功
    } else {
        msg.sentStatus = SentStatusFailed;
    }
    
    // 保存到数据库
    [[IMMessageManager shareInstance] saveMessage:msg];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [IMMessageReceiver postSendMessageResultNotification:msg];
    });
}

+ (void)sendCommandMessage:(GCDAsyncSocket *)sock message:(IMCommandMessage *)msg {
    [sock writeData:[msg sendData] withTimeout:-1 tag:2];
}

+ (void)processReceiveMessage:(NSInteger)code content:(NSString *)content {
    NSLog(@"code= %ld content=%@", code, content);
    
    content = [self processReceiveContent:content];
    if (code == CMD_USER_LOGIN) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [IMLoginReceiver postLoginNotification:content];
        });
        return;
    }
    // 异地登陆
    if (code == CMD_USER_KICK_USER_NOTIFY) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [IMNotificationReceiver postOtherLoginNotification];
        });
        return;
    }
    // 接收到新消息
    if (code == CMD_USER_CHAT_MSG) {
        IMUserMessage * msg = [[IMTextMessage alloc] initWithMessageId:[IMTool productMessageId] content:content];
        // 没有打开推送，说明当前正在聊天界面，收到信息标示为已读
        if (![IMCore shareInstance].messageNotification) {
            [msg markReadStatus];
        }
        // 保存到数据库
        [[IMMessageManager shareInstance] saveMessage:msg];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            // 当前打开推送
            if ([IMCore shareInstance].messageNotification) {
                // 发送推送
                [IMNotificationReceiver postMessageNotification:msg];
            } else {
                // 发送新消息通知
                [IMMessageReceiver postReceiveMessageNotification:msg];
            }
        });
        return;
    }
}

// socket传输过来的字符串处理下，不然解析json的时候会报错
+ (NSString *)processReceiveContent:(NSString *)content {
    NSRange range = [content rangeOfString:@"}" options:NSBackwardsSearch];
    if(range.location != NSNotFound){
        content = [content substringWithRange:NSMakeRange(0, range.location + 1)];
    }
    return content;
}
@end
